import axios, {AxiosRequestConfig, AxiosResponse} from 'axios';
import {settings} from '@/config/Settings';
import {store} from '@/store/Store';
import {getClientId} from '@/base/util/App';
import {RestClient} from '@/base/RestClient';
import Cookies from 'js-cookie';
import {authBloc} from '@/store/module/Auth';

export const baseUrl = process.env.NODE_ENV === 'development' ? settings.baseUrl.dev : settings.baseUrl.pro;

const instance = axios.create({
  baseURL: baseUrl,
  headers: {'Client-Id': getClientId()}
});

instance.interceptors.request.use((config: AxiosRequestConfig) => {
  const token = store.state.auth.accessToken;
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token;
    // config.headers = {'Content-Type':'application/x-www-form-urlencoded;charset=UTF-8'}
  }
  return config;
}, (error: any) => {
  return Promise.reject(error);
});

instance.interceptors.response.use((res: AxiosResponse) => {
  const {data} = res;
  if (data.name && data.name !== '0') {
    console.warn(res.config.method, res.config.url, res.data);
    const err: any = {name: data.name, message: data.message};
    return Promise.reject(err);
  } else {
    return res;
  }
}, (error: any) => {
  console.error(error);
  if (error.response.status === 403 || error.response.status === 401 || store.state.auth.accessToken === '') {
    authBloc.logout();
    Cookies.remove('accessToken');
    // @ts-ignore
    window.location = `${location.origin}/login`;
    window.location.reload();
  }
  return Promise.reject(error);
});

export const request = new RestClient(instance);
